const {
  mysql
} = require('../qcloud')
const axios = require('axios')
const qs = require('qs')
require('pinyin4js') //获取拼音
const md5 = require('md5')

module.exports = async (ctx) => {
  let dt = new Date();
  let yy = dt.getFullYear(),
    mm = (dt.getMonth() + 1).toString().padStart(2, 0),
    dd = (dt.getDate()).toString().padStart(2, 0)
  let dateLine = `${yy}-${mm}-${dd}`
  await mysql('counter')
    .where('dict_date', dateLine)
    .increment('dict_search_count', 1)
  let date = new Date().toLocaleString().replace(/\//g, '-').replace(/[\u4e00-\u9fa5]/g, '');
  if (ctx.request.body.from == 'zh') {
    let resTxt = await axios({
      method: 'post',
      url: "http://api.hcicloud.com:8880/mt/Translate",
      headers: {
        'x-app-key': '345d54aa',
        'x-sdk-version': '5.0',
        'x-request-date': date,
        'x-task-config': 'capkey=mt.cloud.cn2uy,splitsentence=yes',
        'x-session-key': md5(date + '4fc224832ecc57967bec02e89aa5a065'),
        'x-result-format': 'json',
        'x-udid': "101:1234567890"
      },
      data: ctx.request.body.txt
    }).then(res => {
      return res.data.ResponseInfo.ResultText
    })
    let zhtxt = ctx.request.body.from == 'zh' ? ctx.request.body.txt : resTxt;
    let pinyin = PinyinHelper.convertToPinyinString(zhtxt, ' ', PinyinFormat.WITH_TONE_MARK)
    ctx.state.data = {
      'res_txt': resTxt,
      'pin': pinyin
    }
  }
  if (ctx.request.body.from == 'uy') {
    let resTxt = await axios({
      method: 'post',
      url: "http://api.hcicloud.com:8880/mt/Translate",
      headers: {
        'x-app-key': '345d54aa',
        'x-sdk-version': '5.0',
        'x-request-date': date,
        'x-task-config': 'capkey=mt.cloud.uy2cn,splitsentence=yes',
        'x-session-key': md5(date + '4fc224832ecc57967bec02e89aa5a065'),
        'x-result-format': 'json',
        'x-udid': "101:1234567890"
      },
      data: ctx.request.body.txt

    }).then(res => {
      return res.data.ResponseInfo.ResultText;
    })
    // console.log(resTxt);
    let zhtxt = ctx.request.body.from == 'zh' ? ctx.request.body.txt : resTxt;
    let pinyin = PinyinHelper.convertToPinyinString(zhtxt, ' ', PinyinFormat.WITH_TONE_MARK)
    ctx.state.data = {
      'res_txt': resTxt,
      'pin': pinyin,
    }
  }
}
